const SwaggerGenerator = require('./swaggerGenerator');

/**
 * 创建带有自动Swagger文档的路由
 * @param {Object} router - Express路由器
 * @param {string} method - HTTP方法
 * @param {string} path - 路由路径
 * @param {Object} swaggerConfig - Swagger配置
 * @param {Function} handler - 路由处理函数
 */
function createDocumentedRoute(router, method, path, swaggerConfig, handler) {
  // 生成Swagger注释
  const swaggerDoc = SwaggerGenerator.generateRouteDoc(
    method.toUpperCase(),
    path,
    swaggerConfig.summary,
    swaggerConfig.tag,
    swaggerConfig.options
  );
  
  // 打印Swagger注释（用于复制到文件中）
  console.log(`\n// 为路由 ${method.toUpperCase()} ${path} 生成的Swagger注释:`);
  console.log(swaggerDoc);
  
  // 创建路由
  router[method.toLowerCase()](path, handler);
}

/**
 * 批量创建带文档的路由
 * @param {Object} router - Express路由器
 * @param {Array} routeConfigs - 路由配置数组
 */
function createMultipleDocumentedRoutes(router, routeConfigs) {
  routeConfigs.forEach(config => {
    createDocumentedRoute(
      router,
      config.method,
      config.path,
      {
        summary: config.summary,
        tag: config.tag,
        options: config.options
      },
      config.handler
    );
  });
}

/**
 * 路由配置构建器
 */
class RouteBuilder {
  constructor(tag) {
    this.tag = tag;
    this.routes = [];
  }

  /**
   * 添加GET路由
   */
  get(path, summary, options = {}, handler) {
    this.routes.push({
      method: 'GET',
      path,
      summary,
      tag: this.tag,
      options,
      handler
    });
    return this;
  }

  /**
   * 添加POST路由
   */
  post(path, summary, options = {}, handler) {
    this.routes.push({
      method: 'POST',
      path,
      summary,
      tag: this.tag,
      options,
      handler
    });
    return this;
  }

  /**
   * 添加PUT路由
   */
  put(path, summary, options = {}, handler) {
    this.routes.push({
      method: 'PUT',
      path,
      summary,
      tag: this.tag,
      options,
      handler
    });
    return this;
  }

  /**
   * 添加DELETE路由
   */
  delete(path, summary, options = {}, handler) {
    this.routes.push({
      method: 'DELETE',
      path,
      summary,
      tag: this.tag,
      options,
      handler
    });
    return this;
  }

  /**
   * 构建所有路由
   */
  build(router) {
    createMultipleDocumentedRoutes(router, this.routes);
    return router;
  }

  /**
   * 生成文档字符串
   */
  generateDocs() {
    return SwaggerGenerator.generateCompleteDoc(
      this.routes,
      this.tag,
      `${this.tag} API接口`
    );
  }
}

module.exports = {
  createDocumentedRoute,
  createMultipleDocumentedRoutes,
  RouteBuilder
};